//@ts-nocheck
import React, { useEffect, useState, useReducer } from 'react';
const initialState = 0;

function reducer(state: any, action: any) {
  switch (action.type) {
  case 'increment':
    return { number: state.number + 1 };
  case 'decrement':
    return { number: state.number - 1 };
  default:
    throw new Error();
  }
}
function init(initialState: any) {
  return { number: initialState }; // 这就相当于格式化 initialState
}

//用新的dispatch替代老的dispatch
function useLogger(reducer: any, initialState: any, init: any) {
  console.log('useLogger');
  const [state, dispatch] = useReducer(reducer, initialState, init);
  const dispatchWithLogger = (action: any) => {
    console.log('老状态', state);
    dispatch(action);
  };
  //↓组件重新渲染后才会执行
  useEffect(function () {
    console.log('新状态', state);
  }, [state]);
  return [state, dispatchWithLogger];
}

export default function Counter() {
  console.log('Counter1');
  const [state, dispatch] = useLogger(reducer, initialState, init);
  console.log('Counter2');
  /* 初始化时打印如下
    logger.tsx:41 Counter1
    logger.tsx:28 useLogger
    logger.tsx:43 Counter2
    logger.tsx:36 新状态 {number: 0}
  */
  /* 点击后打印如下
    logger.tsx:31 老状态 {number: 0}
    logger.tsx:41 Counter1
    logger.tsx:28 useLogger
    logger.tsx:43 Counter2
    logger.tsx:36 新状态 {number: 1}
  */
  return (
    <>
      Count: {state.number}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  )
}
